package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/order")
@RestController
@Slf4j
public class OrdersController {
    @Autowired
    public OrdersService ordersService;
    @Autowired
    public AddressBookService addressBookService;
    @Autowired
    public ShoppingCartService shoppingCartService;
    @Autowired
    public OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;


    /**
     * 添加用户下单后数据
     * @param submitMp
     * @return
     */
    @PostMapping("/submit")
    @Transactional
    //  评论 付款方式 地址簿ID
    public R<String> post(@RequestBody Map<String,String> submitMp){
        String remark = submitMp.get("remark");//评论
        String payMethod = submitMp.get("payMethod");//付款方式
        String addressBookId = submitMp.get("addressBookId");//地址簿ID  如1631243179409866753

        //拿到地址
        LambdaQueryWrapper<AddressBook> wrapper1=new LambdaQueryWrapper<>();
        wrapper1.eq(AddressBook::getId,addressBookId);
        AddressBook addressBook = addressBookService.getOne(wrapper1);

        //拿购物车
        LambdaQueryWrapper<ShoppingCart> wrapper2=new LambdaQueryWrapper<>();
        wrapper2.eq(ShoppingCart::getUserId,addressBook.getUserId());
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper2);

        //拿购物车
        LambdaQueryWrapper<User> wrapper3=new LambdaQueryWrapper<>();
        wrapper3.eq(User::getId,addressBook.getUserId());
        User user = userService.getOne(wrapper3);

        //把订单信息添加到表中
        Orders orders=new Orders();
        //随机生成订单号
        Random random = new Random();
        String number =""+ random.nextInt(9999);
        orders.setNumber(number);
        orders.setStatus(2);
        orders.setUserId(addressBook.getUserId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(Integer.parseInt(payMethod));
        //金额
        BigDecimal moneys = moneys(shoppingCartList);
        orders.setAmount(moneys);
        orders.setRemark(remark);
        orders.setAddressBookId(addressBook.getId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserName(user.getName());
        //添加到数据库
        ordersService.save(orders);


        //把订单明细添加到表中
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orders.getId());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(moneys);
            orderDetailService.save(orderDetail);
        }
        return R.success("ok");
    }

    /**
     * 计算金额
     * @param shoppingCartList
     */
    private BigDecimal moneys(List<ShoppingCart> shoppingCartList) {
        int moneys=0;
        for (ShoppingCart shoppingCart : shoppingCartList) {
            BigDecimal amount = shoppingCart.getAmount();
            moneys+=amount.intValue();
        }
        BigDecimal money=new BigDecimal(0);
        money=BigDecimal.valueOf(moneys);
        return money;
    }

    /**
     * 查看订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> pageR(int page,int pageSize){
        Page<OrdersDto> ordersPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        List<Orders> list = ordersService.list(wrapper);
        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        ArrayList<OrdersDto> lists=new ArrayList<>();
        for (Orders orders : list) {
            OrdersDto ordersDto=new OrdersDto();
            ordersDto.setUserName(orders.getUserName());
            ordersDto.setPhone(orders.getPhone());
            ordersDto.setAmount(orders.getAmount());
            ordersDto.setConsignee(orders.getConsignee());
            queryWrapper.eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            lists.add(ordersDto);
        }
        ordersPage.setRecords(lists);
        //ordersService.page(ordersPage,wrapper);
        return R.success(ordersPage);
    }

    /**
     * 页面查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    //?page=1&pageSize=10
    public R<Page> get(@RequestParam int page,int pageSize){
        log.info(String.valueOf(page),pageSize);
        Page<Orders> ordersPage=new Page<>(page,pageSize);
        ordersService.page(ordersPage);
        return R.success(ordersPage);
    }

    @PutMapping()
    public R orderUpdate(@RequestBody Map<String,String> orders){
        String id = orders.get("id");
        String status = orders.get("status");//待修改状态
        LambdaQueryWrapper<Orders> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId,id);
        Orders order = ordersService.getOne(wrapper);
        order.setStatus(Integer.parseInt(status));
        boolean b = ordersService.updateById(order);
        return R.success(b);
    }

}
